import { defineStore } from 'pinia';
import { Message } from '@arco-design/web-vue';
import {
  getInventoryList,
  getInventoryDetail,
  adjustInventory,
  getInventoryAlerts,
  getProductLocations,
  getAvailableLocations,
  getLocationInventory,
  getInventoryCountList,
  createInventoryCount,
  getInventoryCountDetail,
  completeInventoryCount
} from '@/api/inventory';
import { warehouseApi } from '@/api';

export const useInventoryStore = defineStore('inventory', {
  state: () => ({
    inventoryList: [],
    inventoryDetail: null,
    alertsList: [],
    productLocations: [],
    locationProducts: [],
    countList: [],
    countDetail: null,
    loading: {
      list: false,
      detail: false,
      alerts: false,
      productLocations: false,
      locationProducts: false,
      countList: false,
      countDetail: false,
      adjust: false,
      createCount: false,
      completeCount: false
    },
    pagination: {
      total: 0,
      current: 1,
      pageSize: 10
    }
  }),

  actions: {
    // 获取库存列表
    async getInventoryList(params = {}) {
      this.loading.list = true;
      try {
        const response = await getInventoryList({
          page: params.page || this.pagination.current,
          pageSize: params.pageSize || this.pagination.pageSize,
          cargo_code: params.cargo_code || params.cargoCode,
          cargo_name: params.cargo_name || params.cargoName,
          warehouse_id: params.warehouse_id || params.warehouseId,
          category_id: params.category_id || params.categoryId
        });
        
        // 检查响应格式，根据实际API返回结构调整处理逻辑
        if (response && response.data) {
          // 兼容不同的响应格式
          const list = response.data.list || response.data.items || [];
          const total = response.data.total || 0;
          
          // 打印一条日志，方便调试
          console.log('库存API返回的原始数据:', list);
          
          // 处理列表数据，确保对象格式一致性并提取必要字段到顶层
          const processedList = list.map(item => {
            // 确保批次信息存在，创建默认值
            const now = new Date();
            const defaultBatchNo = `BATCH-${now.getFullYear()}${(now.getMonth()+1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}-${item.id}`;
            const defaultProductionDate = new Date(now.getTime());
            defaultProductionDate.setDate(defaultProductionDate.getDate() - 30); // 30天前
            const defaultExpiryDate = new Date(now.getTime());
            defaultExpiryDate.setDate(defaultExpiryDate.getDate() + 180); // 180天后

            // 从嵌套对象提取字段到扁平结构
            let flattenedItem = {
              ...item,
              
              // 批次信息 
              batch_no: item.batch_no || item.batchNo || defaultBatchNo,
              batchNo: item.batchNo || item.batch_no || defaultBatchNo,
              
              // 日期信息
              production_date: item.production_date || item.productionDate || defaultProductionDate,
              productionDate: item.productionDate || item.production_date || defaultProductionDate,
              expiry_date: item.expiry_date || item.expiryDate || defaultExpiryDate,
              expiryDate: item.expiryDate || item.expiry_date || defaultExpiryDate,
            };
            
            // 从cargo对象提取字段到扁平结构
            if (item.cargo) {
              flattenedItem.cargo_id = item.cargo.id || item.cargo_id;
              flattenedItem.cargo_code = item.cargo.code || item.cargo_code;
              flattenedItem.cargo_name = item.cargo.name || item.cargo_name;
              flattenedItem.unit = item.cargo.unit || item.unit;
              
              // 从cargo.category提取字段
              if (item.cargo.category) {
                flattenedItem.category_id = item.cargo.category.id || item.category_id;
                flattenedItem.category_name = item.cargo.category.name || item.category_name;
              }
              
              // 从cargo.supplier提取字段
              if (item.cargo.supplier) {
                flattenedItem.supplier_id = item.cargo.supplier.id || item.supplier_id;
                flattenedItem.supplier_name = item.cargo.supplier.name || item.supplier_name;
              }
            }
            
            // 从warehouse对象提取字段
            if (item.warehouse) {
              flattenedItem.warehouse_id = item.warehouse.id || item.warehouse_id;
              flattenedItem.warehouse_name = item.warehouse.name || item.warehouse_name;
            }
            
            // 从location对象提取字段
            if (item.location) {
              flattenedItem.location_id = item.location.id || item.location_id;
              flattenedItem.location_code = item.location.code || item.location_code;
            }
            
            return flattenedItem;
          });
          
          console.log('处理后的库存列表:', processedList);
          
          this.inventoryList = processedList;
          this.pagination.total = total;
          
          return {
            list: processedList, 
            total,
            page: params.page || this.pagination.current,
            pageSize: params.pageSize || this.pagination.pageSize
          };
        }
        return { list: [], total: 0 };
      } catch (error) {
        console.error('获取库存列表失败:', error);
        // 错误时不显示消息弹窗，由调用方决定是否显示
        return { list: [], total: 0 };
      } finally {
        this.loading.list = false;
      }
    },

    // 获取库存详情
    async getInventoryDetail(id) {
      if (!id) return null;
      this.loading.detail = true;
      try {
        const { data } = await getInventoryDetail(id);
        this.inventoryDetail = data;
        return data;
      } catch (error) {
        console.error('获取库存详情失败:', error);
        Message.error('获取库存详情失败');
        return null;
      } finally {
        this.loading.detail = false;
      }
    },

    // 调整库存
    async adjustInventory(id, data) {
      this.loading.adjust = true;
      try {
        console.log('调用库存调整API，ID:', id, '数据:', data);
        
        // 检查数据格式，如果必要的话转换参数名称
        // 后端期望的字段: cargo_id, location_id, adjust_quantity, remark
        const adjustData = {
          cargo_id: data.cargo_id,
          location_id: data.location_id,
          adjust_quantity: data.adjust_quantity,
          remark: data.remark
        };
        
        const response = await adjustInventory(id, adjustData);
        // 移除重复的成功消息，由组件负责显示成功提示
        // Message.success('库存调整成功');
        return response.data;
      } catch (error) {
        console.error('库存调整失败:', error);
        Message.error(`库存调整失败: ${error.message || '未知错误'}`);
        throw error; // 抛出错误以便调用方处理
      } finally {
        this.loading.adjust = false;
      }
    },

    // 获取库存预警
    async getInventoryAlerts(params = {}) {
      this.loading.alerts = true;
      try {
        const { data } = await getInventoryAlerts(params);
        this.alertsList = data.items || [];
        return data;
      } catch (error) {
        console.error('获取库存预警失败:', error);
        Message.error('获取库存预警失败');
        return null;
      } finally {
        this.loading.alerts = false;
      }
    },

    // 获取商品库存位置信息
    async getProductLocations(productId, params = {}) {
      if (!productId) return [];
      this.loading.productLocations = true;
      try {
        const { data } = await getProductLocations(productId, params);
        this.productLocations = data || [];
        return data;
      } catch (error) {
        console.error('获取商品库存位置失败:', error);
        Message.error('获取商品库存位置失败');
        return [];
      } finally {
        this.loading.productLocations = false;
      }
    },

    // 获取库位库存信息
    async getLocationInventory(locationId, params = {}) {
      if (!locationId) {
        console.warn('调用getLocationInventory时未提供locationId');
        return { list: [], total: 0 };
      }
      
      this.loading.locationProducts = true;
      try {
        const response = await getLocationInventory(locationId, params);
        console.log('库位库存API返回原始数据:', response);
        
        // 检查响应格式 - 确保数据结构一致
        if (response && response.data) {
          const { list = [], total = 0, page = 1, size = 10 } = response.data;
          
          // 转换字段名称并添加默认批次信息
          const transformedList = list
            .filter(item => 
              // 过滤条件：必须有有效的货物信息且数量大于0
              item && 
              item.cargo && 
              item.cargo.id && 
              item.quantity > 0
            )
            .map(item => {
            // 生成默认批次信息
            const now = new Date();
            const defaultBatchNo = `BATCH-${now.getFullYear()}${(now.getMonth()+1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}-${item.id}`;
            const defaultProductionDate = new Date(now.setDate(now.getDate() - 30)); // 30天前
            const defaultExpiryDate = new Date();
            defaultExpiryDate.setDate(defaultExpiryDate.getDate() + 180); // 180天后
            
            // 创建一个新对象，防止修改原始数据
            return {
              ...item,
              // 添加驼峰命名的属性，同时保留原始属性
              batchNo: item.batch_no || item.batchNo || defaultBatchNo,
              productionDate: item.production_date || item.productionDate || defaultProductionDate,
              expiryDate: item.expiry_date || item.expiryDate || defaultExpiryDate
            };
          });
          
          // 检查批次信息
          if (transformedList && transformedList.length > 0) {
            console.log('转换后的批次信息:', {
              batchNo: transformedList[0].batchNo,
              productionDate: transformedList[0].productionDate,
              expiryDate: transformedList[0].expiryDate
            });
          }
          
          this.locationProducts = transformedList;
          return { 
            list: transformedList, 
            total, 
            page, 
            size 
          };
        } else {
          return { list: [], total: 0 };
        }
      } catch (error) {
        console.error('获取库位库存信息失败:', error);
        return { list: [], total: 0 };
      } finally {
        this.loading.locationProducts = false;
      }
    },

    // 获取库存盘点单列表
    async getInventoryCountList(params = {}) {
      this.loading.countList = true;
      try {
        const { data } = await getInventoryCountList({
          page: this.pagination.current,
          pageSize: this.pagination.pageSize,
          ...params
        });
        this.countList = data.items || [];
        this.pagination.total = data.total || 0;
        return data;
      } catch (error) {
        console.error('获取盘点单列表失败:', error);
        Message.error('获取盘点单列表失败');
        return null;
      } finally {
        this.loading.countList = false;
      }
    },

    // 创建库存盘点单
    async createInventoryCount(countData) {
      this.loading.createCount = true;
      try {
        const { data } = await createInventoryCount(countData);
        Message.success('创建盘点单成功');
        return data;
      } catch (error) {
        console.error('创建盘点单失败:', error);
        Message.error('创建盘点单失败');
        return null;
      } finally {
        this.loading.createCount = false;
      }
    },

    // 获取库存盘点单详情
    async getInventoryCountDetail(id) {
      if (!id) return null;
      this.loading.countDetail = true;
      try {
        const { data } = await getInventoryCountDetail(id);
        this.countDetail = data;
        return data;
      } catch (error) {
        console.error('获取盘点单详情失败:', error);
        Message.error('获取盘点单详情失败');
        return null;
      } finally {
        this.loading.countDetail = false;
      }
    },

    // 完成库存盘点
    async completeInventoryCount(id, resultData) {
      if (!id) return null;
      this.loading.completeCount = true;
      try {
        const { data } = await completeInventoryCount(id, resultData);
        Message.success('盘点完成成功');
        return data;
      } catch (error) {
        console.error('盘点完成失败:', error);
        Message.error('盘点完成失败');
        return null;
      } finally {
        this.loading.completeCount = false;
      }
    },

    // 获取可用库位列表
    async getAvailableLocationsList(warehouseId, params = {}) {
      if (!warehouseId) return [];
      this.loading.locationProducts = true;
      try {
        const { data } = await getAvailableLocations(warehouseId, params);
        return data || [];
      } catch (error) {
        console.error('获取可用库位失败:', error);
        Message.error('获取可用库位失败');
        return [];
      } finally {
        this.loading.locationProducts = false;
      }
    },

    // 获取可用上架库位 (添加到 inventory store? 还是 warehouse store? 暂时放这里)
    async getAvailableLocations(warehouseId, params) {
      try {
        const response = await warehouseApi.getAvailableLocations(warehouseId, params); 
        if (response.code === 0) {
          return response.data || []; // 返回库位列表
        } else {
          console.error("获取可用库位失败:", response.message);
          Message.error(response.message || '获取可用库位失败');
          return [];
        }
      } catch (error) {
        console.error("获取可用库位时出错:", error);
        Message.error('获取可用库位时发生网络错误');
        return [];
      }
    },

    // 工具函数：获取库存状态文本
    getStatusText(status) {
      const statusMap = {
        1: '正常',
        2: '库存不足',
        3: '库存过多',
        4: '已禁用',
        'normal': '正常',
        'locked': '已锁定',
        'low': '库存不足',
        'expired': '已过期',
        'damaged': '已损坏'
      };
      return statusMap[status] || '未知状态';
    },

    // 工具函数：获取库存状态颜色
    getStatusColor(status) {
      const colorMap = {
        1: 'green',
        2: 'red',
        3: 'orange',
        4: 'gray',
        'normal': 'green',
        'locked': 'orange',
        'low': 'red',
        'expired': 'gray',
        'damaged': 'red'
      };
      return colorMap[status] || 'blue';
    },

    // 工具函数：获取调整原因文本
    getAdjustReasonText(reason) {
      const map = {
        '1': '盘点调整',
        '2': '损耗调整',
        '3': '系统校正',
        '4': '其他原因'
      };
      return map[reason] || '其他原因';
    }
  }
}); 